var Q = require('q'),
    entityCollection = require('../../../Base/server/controllers/EntityCollection');

// 获取所有有效工位
exports.getStation = function (req, res) {
    var deferred = Q.defer();

    var entity = entityCollection.getEntity("WorkLocation");
    entity.Entity
        .find({IsEffective: true}, {Code: 1, Name: 1})
        .exec(function (err, records) {
            if (err) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询工位错误';
                newErr.message = '获取所有有效工位失败！';
                deferred.reject(newErr);
                return;
            }
            deferred.resolve(records);
        });

    return deferred.promise;
};

// 根据记录ID查找工位
exports.findById = function (workLocationId, projection, populate) {
    var deferred = Q.defer();

    if (!projection) {
        projection = {};
    }
    var entity = entityCollection.getEntity("WorkLocation"),
        result = entity.Entity.findById(workLocationId, projection);
    if (populate) {
        result = result.populate(populate);
    }

    result.then(function (record) {
        deferred.resolve(record);
    }, function () {
        var newErr = new Error();
        newErr.leval = 9;
        newErr.title = '查询工位错误';
        newErr.message = '查询失败，请检查查询参数！';
        deferred.reject(newErr);
    });

    return deferred.promise;
};

//查找部门下所有工位
exports.findByDepartment = function (departments, completeFun) {
    var entity = entityCollection.getEntity("WorkLocation");
    entity.find({Department: {$in: departments}, IsEffective: true}, null, null, function (err, records) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询工位错误';
            newErr.message = '请检查查询参数！';
            completeFun(newErr);
        } else {
            completeFun(null, records);
        }
    });
};
